#!/usr/bin/env python3
"""
对话搜索功能调试脚本
直接测试对话搜索的各个组件
"""

import asyncio
import sys
import os
from datetime import datetime

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

# 直接导入需要的模块
from database.mongodb_client import MongoDBClient
from database.chromadb_client import ChromaDBClient
from core.conversation_manager import ConversationManager
from database.manager import DatabaseManager
from config import load_config

async def debug_conversation_search():
    """调试对话搜索功能"""
    print("=== 对话搜索调试开始 ===")
    
    try:
        # 1. 加载配置
        print("\n1. 加载配置...")
        config = load_config()
        print("✅ 配置加载成功")
        
        # 2. 初始化数据库管理器
        print("\n2. 初始化数据库管理器...")
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        print("✅ 数据库管理器初始化成功")
        
        # 3. 初始化对话管理器
        print("\n3. 初始化对话管理器...")
        conversation_manager = ConversationManager(db_manager)
        print("✅ 对话管理器初始化成功")
        
        # 4. 检查MongoDB中的对话数据
        print("\n4. 检查MongoDB中的对话数据...")
        mongodb_client = db_manager.mongodb_client
        conversations_collection = mongodb_client.get_collection('conversations')
        
        # 查询所有对话
        all_conversations = list(conversations_collection.find({}).limit(5))
        print(f"MongoDB中共有 {conversations_collection.count_documents({})} 个对话")
        
        if all_conversations:
            print("最近的5个对话:")
            for conv in all_conversations:
                print(f"  - ID: {conv.get('conversation_id', conv.get('_id'))}")
                print(f"    用户: {conv.get('user_id')}")
                print(f"    标题: {conv.get('title', 'N/A')}")
                print(f"    时间: {conv.get('created_at', 'N/A')}")
                print(f"    消息数: {len(conv.get('messages', []))}")
                if conv.get('messages'):
                    print(f"    最后消息: {conv['messages'][-1].get('content', '')[:50]}...")
                print()
        else:
            print("❌ MongoDB中没有找到对话数据")
            return
        
        # 5. 检查ChromaDB中的对话向量数据
        print("\n5. 检查ChromaDB中的对话向量数据...")
        chromadb_client = db_manager.chromadb_client
        
        try:
            # 获取对话集合统计
            conversation_stats = await chromadb_client.get_collection_stats('conversations')
            print(f"ChromaDB对话集合统计: {conversation_stats}")
            
            # 检查是否有向量数据
            if conversation_stats.get('count', 0) > 0:
                print("✅ ChromaDB中有对话向量数据")
            else:
                print("❌ ChromaDB中没有对话向量数据")
                
        except Exception as e:
            print(f"❌ 检查ChromaDB对话数据时出错: {e}")
        
        # 6. 直接测试ChromaDB搜索
        print("\n6. 直接测试ChromaDB对话搜索...")
        try:
            # 使用一个通用的搜索词
            search_results = await chromadb_client.search_conversations(
                query="王者荣耀",
                user_id="user_123",
                limit=5
            )
            print(f"ChromaDB搜索结果数量: {len(search_results)}")
            
            if search_results:
                print("搜索结果:")
                for i, result in enumerate(search_results):
                    print(f"  {i+1}. ID: {result.get('id')}")
                    print(f"     内容: {result.get('content', '')[:100]}...")
                    print(f"     距离: {result.get('distance', 'N/A')}")
                    print()
            else:
                print("❌ ChromaDB搜索没有返回结果")
                
        except Exception as e:
            print(f"❌ ChromaDB搜索时出错: {e}")
        
        # 7. 测试ConversationManager的搜索
        print("\n7. 测试ConversationManager的搜索...")
        try:
            manager_results = await conversation_manager.search_conversations(
                user_id="user_123",
                query="王者荣耀",
                limit=5
            )
            print(f"ConversationManager搜索结果数量: {len(manager_results)}")
            
            if manager_results:
                print("搜索结果:")
                for i, result in enumerate(manager_results):
                    print(f"  {i+1}. 会话ID: {result.get('session_id')}")
                    print(f"     标题: {result.get('title', 'N/A')}")
                    print(f"     最后消息: {result.get('last_message', '')[:100]}...")
                    print(f"     时间: {result.get('timestamp', 'N/A')}")
                    print()
            else:
                print("❌ ConversationManager搜索没有返回结果")
                
        except Exception as e:
            print(f"❌ ConversationManager搜索时出错: {e}")
            import traceback
            traceback.print_exc()
        
        # 8. 检查具体的对话获取
        print("\n8. 检查具体的对话获取...")
        if all_conversations:
            test_conv_id = all_conversations[0].get('conversation_id', all_conversations[0].get('_id'))
            try:
                conversation_details = await conversation_manager.get_conversation(
                    session_id=str(test_conv_id),
                    user_id="user_123"
                )
                if conversation_details:
                    print(f"✅ 成功获取对话详情: {test_conv_id}")
                    print(f"   消息数量: {len(conversation_details.get('messages', []))}")
                else:
                    print(f"❌ 无法获取对话详情: {test_conv_id}")
            except Exception as e:
                print(f"❌ 获取对话详情时出错: {e}")
        
        # 9. 检查对话消息
        print("\n9. 检查对话消息...")
        messages_collection = mongodb_client.get_collection('conversation_messages')
        message_count = messages_collection.count_documents({})
        print(f"MongoDB中共有 {message_count} 条对话消息")
        
        if message_count > 0:
            sample_messages = list(messages_collection.find({}).limit(3))
            print("示例消息:")
            for msg in sample_messages:
                print(f"  - 会话ID: {msg.get('session_id')}")
                print(f"    内容: {msg.get('content', '')[:100]}...")
                print(f"    角色: {msg.get('role')}")
                print(f"    时间: {msg.get('timestamp')}")
                print()
        
    except Exception as e:
        print(f"❌ 调试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 清理资源
        try:
            if 'db_manager' in locals():
                await db_manager.close()
                print("\n✅ 数据库连接已关闭")
        except Exception as e:
            print(f"❌ 关闭数据库连接时出错: {e}")
    
    print("\n=== 对话搜索调试结束 ===")

if __name__ == "__main__":
    asyncio.run(debug_conversation_search())